package org.demo.nio.reactor.simple;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by tangwy on 2017/10/30.
 */
public class SimpleReactor implements Runnable {
    private Selector selector;
    private ServerSocketChannel ssc;

    public SimpleReactor(int port) throws IOException {
        this(new InetSocketAddress(port));
    }

    public SimpleReactor(String ip, int port) throws IOException {
        this(new InetSocketAddress(ip, port));
    }

    public SimpleReactor(SocketAddress address) throws IOException {
        ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.socket().bind(address);
        selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT, new Acceptor(selector, ssc));
    }

    @Override
    public void run() {
        while (!Thread.interrupted()) {
            try {
                int keys = selector.select(500L);
                if (keys > 0) {
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        process(key);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void process(SelectionKey key) {
        Runnable handler = (Runnable) key.attachment();
        if (handler != null) {
            handler.run();
        }
    }
}
